package evobot {
	
	public class GameClient	{
		static private var _instance:GameClient = new GameClient();
		internal var VERSION:String = "091103_11";
		private var connection:Connection = null;
		public var connected:Boolean = false;
		private var player:Object = null;
		private var log:Log = Log.getInstance();
		
		public function GameClient() {	
			if (_instance != null){ 
                throw new Error("GameClient can only be accessed through GameClient.getInstance()");
            }
		}
				
		static public function getInstance():GameClient {
			return _instance;
		}
		
		private var loginDispatch:Function = null;
		public function login(host:String, port:uint, user:String, password:String, callback:Function):void {
			this.loginDispatch = callback;
			connection = new Connection(host, port, user, password);
		}
		
		internal function loginResponse(data:Object):void {
			if (connected) return; // Sometimes you get a sandbox violation after you log in because a previous
								   // failed attempt will timeout on downloading the cross domain policy.			
			if (data.ok != 1) {
				// ok = -2 incorrect account or password
				// ok = -4 need to create a player
				// ok = -100 invalid server
				// ok = -101 security doesn't allow us to reach the internet
				// ok = -102 network timeout
				// ok = -103 invalid paramters
				if (loginDispatch != null) {
					loginDispatch(data.ok, data.errorMsg);
					loginDispatch = null;
				}
				connection.close();
				connection = null;
				return;
			}
						
			player = data.player; // check evobot/Player.as to see what is in there
			connected = true;
			if(loginDispatch != null) {
				loginDispatch(1,"Login Successful");
				loginDispatch = null;
			}
			log.write("Logged in");			
		}
		
		internal function lostConnection():void {
			connection = null;
			if(!connected) {
				if(loginDispatch != null) {
					loginDispatch(-104,"Lost connection while connecting to server!");
					loginDispatch = null;
				}
			} else {
				log.write("Disconnected from server.");
				connected = false;
				// You would add reconnect code here.
			}	
		}
		
		internal function otherLogin():void {
			connected = false;
			connection.close();
			connection = null;
			log.write("Your account has been logged in from somewhere else.");
			// You probably don't want to attempt to reconnect when this happens.
		}
		
		internal function channelChatMsg(data:Object):void {
			log.write(data.channel + " " + data.fromUser + "> " + data.msg); 			
		}
	} 
}